//
//	 ______    ______    ______    
//	/\  __ \  /\  ___\  /\  ___\   
//	\ \  __<  \ \  __\_ \ \  __\_ 
//	 \ \_____\ \ \_____\ \ \_____\ 
//	  \/_____/  \/_____/  \/_____/ 
//
//	Powered by BeeFramework
//
//
//  AddPet.m
//  DingDing
//
//  Created by LHL on 14/11/22.
//  Copyright (c) 2014年 com.gordon. All rights reserved.
//

#import "AddPet.h"
#import "Common.h"
#import "ChoosePets.h"
#import "EditPetsDocument.h"
#import "AddPetCell.h"
#import <MapKit/MapKit.h>
#import "AFHTTPRequestOperation.h"
#import "MainNearBy_Board.h"
#pragma mark -

@interface AddPet()
{
	//<#@private var#>
}
@end

@implementation AddPet{
    CustomDatePiker *piker; //自定义日期控件
    UIImagePickerController *imagePicker; //选择头像
    NSString *currenIndex;
    BOOL _isTrans; //是否已上传头像
    PETMODEL *currentModel;
}

SUPPORT_AUTOMATIC_LAYOUT( YES )
SUPPORT_RESOURCE_LOADING( YES )

DEF_MODEL(addPets, iaddPets)
DEF_MODEL(addPetHead, iaddPetHead)
DEF_OUTLET(BeeUIScrollView, list)
- (void)load
{
    self.iaddPets = [addPets modelWithObserver:self];
    self.iaddPetHead = [addPetHead modelWithObserver:self];
    
}
- (void)unload
{
    
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return [gestureRecognizer isKindOfClass:UIScreenEdgePanGestureRecognizer.class];
}

#pragma mark - Signal

ON_CREATE_VIEWS( signal )
{

    _isTrans = NO;
    self.navigationBarShown = YES;
    self.navigationItem.hidesBackButton = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"添加宠物";
    [BeeUINavigationBar setTitleColor:[UIColor whiteColor]];
//    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    piker = [[CustomDatePiker alloc]init];
    [piker getAge:^(NSString  *agestr,NSInteger age){
        BeeUIScrollItem *item = self.list.items[0];
        AddPetCell * cell = (AddPetCell *)item.view;
        if (age>=12) {
            cell.petAgeLabel.text = [NSString stringWithFormat:@"%d岁%d个月",age/12,age%12];
        }else{
            cell.petAgeLabel.text = [NSString stringWithFormat:@"%ld个月",(long)age];
        }
        [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%d",age] forKey:@"petage"];
        [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%d",age] forKey:@"petagestr"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        self.iaddPets.age = agestr;
    }];
    self.list.lineCount=1;
    self.list.whenReloading=^{
        self.list.total = 1;
        for (BeeUIScrollItem *item in self.list.items) {
            item.clazz = [AddPetCell class];
            item.size = CGSizeMake(self.list.width, [UIScreen mainScreen].bounds.size.height);
        }
    };

}
- (void)pickImageFromAlbum{
    imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.allowsEditing = YES;
    [[UINavigationBar appearance]setBackgroundImage:[UIImage imageNamed:@"title.png"] forBarMetrics:UIBarMetricsDefault];
    [self presentViewController:imagePicker animated:YES completion:^{
        
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image= [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera){
        
    }
    NSInteger imglength = [UIImageJPEGRepresentation(image, 1.0) length];
    NSData *small = UIImageJPEGRepresentation(image, (imglength %10)/imglength);
    UIImage *final = [Common imageWithImageSimple:[UIImage imageWithData:small] scaledToSize:CGSizeMake(180, 180)];
    [[NSUserDefaults  standardUserDefaults]setObject:UIImageJPEGRepresentation(final, 0.75) forKey:@"head_img"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    BeeUIScrollItem *item = self.list.items[0];
    AddPetCell * cell = (AddPetCell *)item.view;
    [cell.addPhoto setBackgroundImage:final forState:0];
    
    [imagePicker dismissViewControllerAnimated:YES completion:^{
        [self.iaddPetHead firstPage];
    }];
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
     [picker dismissViewControllerAnimated:YES completion:NULL];
    NSLog(@"cancel");
}
ON_SIGNAL3(AddPetCell, addPhoto, SGINAL){
    [self pickImageFromAlbum];
}

ON_DELETE_VIEWS( signal )
{
    
}

ON_LAYOUT_VIEWS( signal )
{
}

ON_WILL_APPEAR( signal )
{
    [[UINavigationBar appearance]setBackgroundImage:[UIImage imageNamed:@"title.png"] forBarMetrics:UIBarMetricsDefault];
}

ON_DID_APPEAR( signal )
{
    
}

ON_WILL_DISAPPEAR( signal )
{

}

ON_DID_DISAPPEAR( signal )
{
}

ON_SIGNAL3( BeeUINavigationBar, LEFT_TOUCHED, signal )
{
    
}

ON_SIGNAL3( BeeUINavigationBar, RIGHT_TOUCHED, signal )
{
}

ON_SIGNAL3(addPetHead, RELOADED, SIGNAL){
    [self dismissTips];
    _isTrans = YES;
    [self presentMessageTips:@"上传成功"];
    NSLog(@"上传成功");
}

ON_SIGNAL3(addPetHead, RELOADING, SIGNAL){
    [self presentLoadingTips:@"加载中"];
}

ON_SIGNAL3(addPets, RELOADED, SIGNAL){
    [self dismissTips];
    if ([self.iaddPets.code isEqualToString:@"200"]) {
        [self presentMessageTips:@"添加成功"];
//        MainNearBy_Board *main = [[MainNearBy_Board alloc]init];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"loginsuccess" object:nil];
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }else{
        [self presentMessageTips:self.iaddPets.message];
    }
}


ON_SIGNAL3(addPets, RELOADING, SIGNAL){
    [self presentLoadingTips:@"加载中"];
}

//#pragma mark - Location
//
//- (void)locationManager:(CLLocationManager *)manager
//    didUpdateToLocation:(CLLocation *)newLocation
//           fromLocation:(CLLocation *)oldLocation{
//    [locationmanager stopUpdatingLocation];
//    NSString *strlat = [NSString stringWithFormat:@"%f",newLocation.coordinate.latitude];
//    NSString *strlng = [NSString stringWithFormat:@"%f",newLocation.coordinate.longitude];
//    NSLog(@"%@----%@",strlat,strlng);
//    [[NSUserDefaults standardUserDefaults]setObject:strlat forKey:@"lat"];
//    [[NSUserDefaults standardUserDefaults]setObject:strlng forKey:@"lnt"];
//    [[NSUserDefaults standardUserDefaults]synchronize];
//    
//}
//- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
//    [self presentMessageTips:[NSString stringWithFormat:@"%@",error]];
//}

#pragma mark - AddPetCell SIGNAL


ON_SIGNAL3(BeeUIButton, petAge, SIGNAL){
    [self.view addSubview:piker];
    [piker showPiker];
}

ON_SIGNAL3(AddPetCell, petType, SIGNAL){
    ChoosePets *choose = [[ChoosePets alloc]init];
    [choose getPetModelBlock:^(PETMODEL *model){
        currentModel = model;
        BeeUIScrollItem *item = self.list.items[0];
        AddPetCell * cell = (AddPetCell *)item.view;
        cell.petTypeLabel.text = model.name;
        currenIndex = model.index;
        [[NSUserDefaults standardUserDefaults]setObject:model.name forKey:@"petvarifyname"];
        [[NSUserDefaults standardUserDefaults]setObject:model.id_ forKey:@"pet_id"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }];
    [self.navigationController pushViewController:choose animated:YES];
}

ON_SIGNAL3(AddPetCell, confirm, SIGNAL){
    BeeUIScrollItem *item = self.list.items[0];
    AddPetCell * cell = (AddPetCell *)item.view;
    if (cell.petName.text.length ==0) {
        [self presentMessageTips:@"请输入宠物的名字"];
        return;
    }
    if (cell.male.selected== NO && cell.female.selected == NO) {
        [self presentMessageTips:@"请选择宠物的性别"];
        return;
    }
    if (cell.petAgeLabel.text.length == 0) {
        [self presentMessageTips:@"请选择宠物的年龄"];
        return;
    }
    if (cell.petTypeLabel.text.length == 0) {
        [self presentMessageTips:@"请选择宠物的种类"];
        return;
    }
    if (!_isTrans) {
        [self presentMessageTips:@"请上传宠物头像"];
        return;
    }
    self.iaddPets.pet_id = currentModel.id_;
    self.iaddPets.petname = cell.petName.text;
    if (cell.male.selected) {
        self.iaddPets.gender = @"male";
    }else{
        self.iaddPets.gender = @"female";
    }
//    self.iaddPets.age = cell.petAgeLabel.text;
    self.iaddPets.variety = currentModel.index;
    [self.iaddPets firstPage];
//    EditPetsDocument *doc = [[EditPetsDocument alloc]init];
//    [self.navigationController pushViewController:doc animated:YES];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    for (BeeUITextField *t  in self.view.subviews) {
        [t resignFirstResponder];
    }
}
ON_SIGNAL3( AddPetCell, RETURN, signal ){
    UITextField *input = (UITextField *)signal.source;
        [input resignFirstResponder];
}

@end
